using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace Validation.Controllers
{
    public class ContactController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Contact()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Contact(string name, string email, string url,
            string subject, string body)
        {
            // Validate Name
            if (string.IsNullOrEmpty(name))
                ModelState.AddModelError("name", "You must enter your name.");

            // Validate Email
            if (string.IsNullOrEmpty(email))
                ModelState.AddModelError("email", "You must enter your email.");
            else
            {
                Regex regex = new Regex
                    (@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
                    RegexOptions.IgnoreCase);

                if (!regex.IsMatch(email))
                    ModelState.AddModelError("email", "You must enter a valid email.");
            }

            // Validate URL
            if (string.IsNullOrEmpty(url))
                ModelState.AddModelError("url", "You must enter your URL.");
            else
            {
                Regex regex = new Regex
                    (@"(?<http>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)",
                    RegexOptions.IgnoreCase);

                if (!regex.IsMatch(url))
                    ModelState.AddModelError("url", "You must enter a valid URL.");
            }

            // Validate Subject
            if (string.IsNullOrEmpty(subject))
                ModelState.AddModelError("subject", "You must enter a subject.");

            // Validate Body
            if (string.IsNullOrEmpty(body))
                ModelState.AddModelError("body", "You must enter the body text.");

            // Send Email
            if (ViewData.ModelState.IsValid)
            {
                MailAddress from = new MailAddress(email, name);
                MailAddress to = new MailAddress("keyvan@wrox.com");

                MailMessage mail = new MailMessage(from, to);
                mail.Subject = subject;
                mail.Body = body;

                SmtpClient smtp = new SmtpClient("mail.wrox.com");
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Send(mail);

                return RedirectToAction("Index", "Home");
            }

            // There is an error, so we display the form with error messages
            return View();
        }
    }
}
